package topcbl.net;

import topcbl.interfaces.BindServiceListener;
import topcbl.net.TaxiService.TaxiBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

/**
 * Class agent to manipulate with service taxi
 * 
 * @author baolong
 * 
 */
public class Bind2Service {
	private TaxiService mService;
	private ServiceConnection mConnection;
	private Context context;
	private boolean isBound = false;
	private BindServiceListener mCallBack;

	public Bind2Service(Context context) {
		mConnection = new ServiceConnection() {

			@Override
			public void onServiceConnected(ComponentName className,
					IBinder service) {
				TaxiBinder binder = (TaxiBinder) service;
				mService = binder.getService();
				if (mCallBack != null)
					mCallBack.onBindMyService();
				isBound = true;
			}

			@Override
			public void onServiceDisconnected(ComponentName arg0) {
				isBound = false;
			}
		};
		this.context = context;
	}

	public void bind() {
		Intent intent = new Intent(context, TaxiService.class);
		context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
	}

	public void unbind() {
		if (isBound)
			context.unbindService(mConnection);
		isBound = false;
	}

	public TaxiService getService() {
		return mService;
	}

	public boolean isBound() {
		return isBound;
	}

	public void setBindServiceListener(BindServiceListener callback) {
		mCallBack = callback;
	}

}
